#include <QtGui>
#include <QtWebKit>
#include <QDebug>
 #include "window.h"

 Window::Window(QWidget *parent)
     : QMainWindow(parent)
 {
     webView = new QWebView();

     this->webView->connect(this->webView, SIGNAL(loadFinished(bool)), this, SLOT(on_webView_loadFinished()));

     setupUi(this);
 }

 void Window::setUrl(const QUrl &url)
 {


     QNetworkProxy proxy;
     proxy.setType(QNetworkProxy::HttpProxy);
     proxy.setHostName(QString("127.0.0.1"));
     proxy.setPort(6666);
     QNetworkProxy::setApplicationProxy(proxy);
     webView->setUrl(url);
     qDebug () << webView->url();

 }

 void Window::on_webView_loadFinished()
 {

     treeWidget->clear();

     QWebFrame *frame = webView->page()->mainFrame();
     QWebElement document = frame->documentElement();
//      qDebug() << webView->page()->mainFrame()->documentElement().toPlainText();
     QWebElementCollection tables = document.findAll("table");
     QWebElementCollection trs = tables.at(3).findAll("tr");
     qDebug () << "Count trs: " << trs.count();


     QString text_rus;
     QString url;
     QString quote_rus;
     QString mana_string;
     int id;

     for (int i  = 0; i < trs.count(); i++)
     {
        QWebElementCollection tds = trs.at(i).findAll("td");
        if (tds.count() == 1)
            continue;


        for(int j = 0; j < tds.count(); j++)
        {
            QWebElement td  = tds.at(j);
            url =  td.findFirst("a").attribute("href");
            QWebElementCollection ps = td.findAll("p");

            text_rus = ps.at(2).toPlainText();
            quote_rus = ps.at(3).toPlainText();
            QString type_mana = ps.at(1).toPlainText();
            if (type_mana.length() > 0 )
            {
                QStringList tmp = type_mana.split(", ");

                if (tmp.size() > 1)
                    mana_string = tmp.at(1);
            }



            qDebug () << "URL: " << url << "\tText: " << text_rus << "Mana: "<< mana_string;


            url.clear();
            text_rus.clear();
            mana_string.clear();
        }

     }

 }

 void Window::examineChildElements(const QWebElement &parentElement,
                                   QTreeWidgetItem *parentItem)
 {
     QWebElement element = parentElement.firstChild();
     while (!element.isNull()) {

         QTreeWidgetItem *item = new QTreeWidgetItem();
         item->setText(0, element.tagName());
         parentItem->addChild(item);

         examineChildElements(element, item);

         element = element.nextSibling();
         qDebug () << element.tagName();
     }
 }
